import { assetsUrl } from "../../config/env";
import { addCart } from "../../apis/cart";
import { addOrder } from "../../apis/order";
import { getGoodsDetail, getGoodsList } from "../../apis/goods";
import Toast from "@vant/weapp/toast/toast";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    assetsUrl,
    goodsPrice: "",
    goodsName: "",
    goodsImg: "",
    goodsId: "",
    compList: [],
  },

  async addToCart() {
    await addCart({
      goodsId: this.data.goodsId,
      goodsNum: 1,
    });
    Toast.success("加入购物车成功");
  },
  async addToOrder() {
    await addOrder({
      goodsList: [
        {
          goodsId: this.data.goodsId,
          goodsNum: 1,
        },
      ],
    });
    Toast.success("加入订单成功");
  },
  async getCompList() {
    const res = await getGoodsList({
      pageNum: 1,
      pageSize: 4,
    });
    this.setData({
      compList: res.list,
    });
  },
  async getDetail(id) {
    const res = await getGoodsDetail(id);
    this.setData({
      goodsPrice: res.goodsPrice,
      goodsName: res.goodsName,
      goodsImg: res.goodsImg,
    });
  },
  handleAction(val) {
    console.log(val);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      goodsId: options.id,
    });
    this.getDetail(options.id);
    this.getCompList();
  },
  gotoDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/detail/index?id=" + id,
    });
  },
  gotoCartPage() {    
    wx.switchTab({
      url: "/pages/cart/index"
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
